// utils/exportExcelWithImage.js
import XLSX from 'xlsx'
import ExcelJS from 'exceljs'
import { saveAs } from 'file-saver';

export async function exportProductionOrderImg(data, fileName = '生产订单.xlsx') {
  // 创建工作簿
  const workbook = new ExcelJS.Workbook();
  const worksheet = workbook.addWorksheet('生产订单');

  // ============= 设置表格样式 =============
  // 标题样式
  const titleStyle = {
    font: { bold: true, size: 14, color: { argb: 'FF000000' } },
    alignment: { horizontal: 'center' }
  };

  // 表头样式
  const headerStyle = {
    font: { bold: true, color: { argb: 'FF000000' } },
    fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF000000' } },
    border: {
      top: { style: 'thin', color: { argb: 'FF000000' } },
      left: { style: 'thin', color: { argb: 'FF000000' } },
      bottom: { style: 'thin', color: { argb: 'FF000000' } },
      right: { style: 'thin', color: { argb: 'FF000000' } }
    },
    alignment: { vertical: 'middle', horizontal: 'center' }
  };

  // 数据单元格样式
  const cellStyle = {
    border: {
      top: { style: 'thin', color: { argb: 'FFD9D9D9' } },
      left: { style: 'thin', color: { argb: 'FFD9D9D9' } },
      bottom: { style: 'thin', color: { argb: 'FFD9D9D9' } },
      right: { style: 'thin', color: { argb: 'FFD9D9D9' } }
    },
    alignment: { vertical: 'middle' }
  };

  // ============= 添加主表数据 =============
  // 添加标题
  worksheet.mergeCells('A1:H1');
  const titleCell = worksheet.getCell('A1');
  titleCell.value = '普通股架, 翻单生产单';
  titleCell.style = titleStyle;

  // 添加主表数据行
  const mainDataRows = [
    ['生产编号', data.productionNo, '客人下单日期', data.orderDate, '尺码', data.size, '生产线', data.productionLine],
    ['客人订单号', data.customerOrderNo, '出货要求交期', data.deliveryDate, '低点', data.lowPoint, '客户代码', data.customerCode],
    ['PLU号', data.pluNo, '订单数', data.orderQuantity, '露车', data.carType, '冲模编号', data.moldNo],
    ['客款号', data.styleNo, '生产数', data.productionQuantity, '开放位', data.openPosition, '', ''],
    ['TS完成日期', data.tsCompletionDate, 'TCS完成日期', data.tcsCompletionDate, '订单类别', data.orderType, '', `提升料:${data.material1}`],
    ['图例', '', '', '', '', '', '', `提升料:${data.material2}`],
    ['图例GAI1824', '', '', '', '', '', '', `提升料:${data.material3}`]
  ];

  // 添加主表数据
  mainDataRows.forEach((row, rowIndex) => {
    const worksheetRow = worksheet.addRow(row);
    // worksheetRow.height = 25; // 设置行高
    
    worksheetRow.eachCell((cell, colNumber) => {
      // 设置表头单元格样式
      if (colNumber % 2 === 1) { // 奇数列为标题列
        cell.style = { ...headerStyle, ...cellStyle };
      } else {
        cell.style = cellStyle;
      }
      
      // 合并最后三行的前七列
      if (rowIndex >= 4 && colNumber <= 7) {
        if (colNumber === 1) {
          worksheet.mergeCells(
            worksheetRow.number, 1, 
            worksheetRow.number, 7
          );
        } else {
          cell.value = ''; // 清空合并单元格的值
        }
      }
    });
  });

  // ============= 添加图片 =============
  // 在中间行添加图片（第6行，第4列位置）
  if (data.imageBase64) {
    const imageId = workbook.addImage({
      base64: data.imageBase64,
      extension: 'png'
    });
    
    // 图片位置：从第6行第4列开始，跨3列
    worksheet.addImage(imageId, {
      tl: { col: 4, row: 5 }, // 第6行(索引5)，第4列
      br: { col: 7, row: 6 }, // 跨到第7列，第7行
      editAs: 'oneCell' // 图片随单元格移动和调整大小
    });
    
    // 设置图片所在单元格的样式
    for (let r = 5; r <= 6; r++) {
      for (let c = 4; c <= 7; c++) {
        const cell = worksheet.getCell(r, c);
        cell.style = {
          ...cellStyle,
          fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFF2F2F2' } }
        };
      }
    }
  }

  // ============= 添加物料清单 =============
  // 添加空行
  worksheet.addRow([]);
  
  // 添加物料清单标题
  const materialTitleRow = worksheet.addRow(['外购物料清单']);
  materialTitleRow.getCell(1).style = titleStyle;
  worksheet.mergeCells(`A${materialTitleRow.number}:F${materialTitleRow.number}`);

  // 添加物料清单表头
  const materialHeader = worksheet.addRow(['类别', '物料编码', '物料描述', '数量', '单位', '备注']);
  materialHeader.height = 25;
  materialHeader.eachCell(cell => {
    cell.style = headerStyle;
  });

  // 添加物料数据
  data.materialList.forEach(item => {
    const row = worksheet.addRow([
      item.category,
      item.materialCode,
      item.materialDescription,
      item.quantity,
      item.unit,
      item.remark
    ]);
    row.height = 25;
    
    // 设置物料描述列自动换行
    const descCell = row.getCell(3);
    descCell.style = { 
      ...cellStyle,
      alignment: { wrapText: true, vertical: 'middle' }
    };
  });

  // ============= 设置列宽 =============
  worksheet.columns = [
    { width: 10 },  // A列: 类别
    { width: 15 },  // B列: 物料编码
    { width: 60 },  // C列: 物料描述
    { width: 8 },   // D列: 数量
    { width: 8 },   // E列: 单位
    { width: 20 },  // F列: 备注
    { width: 12 },  // G列
    { width: 15 }   // H列
  ];

  // ============= 导出文件 =============
  const buffer = await workbook.xlsx.writeBuffer();
  saveAs(new Blob([buffer]), fileName);
}